package models

import (
	"time"

	"gorm.io/gorm"
)

type PushRecord struct {
	ID          uint           `json:"id" gorm:"primaryKey"`
	CustomerID  uint           `json:"customer_id" gorm:"not null"`
	PartnerID   uint           `json:"partner_id" gorm:"not null"`
	PushType    string         `json:"push_type" gorm:"type:enum('manual');not null"` // 只保留手动推送
	Status      string         `json:"status" gorm:"type:enum('pending','success','failed','retry');default:'pending'"`
	MatchScore  float64        `json:"match_score" gorm:"type:decimal(5,2)"`
	MatchType   string         `json:"match_type" gorm:"size:50"`
	Response    string         `json:"response" gorm:"type:text"`
	ErrorMsg    string         `json:"error_message" gorm:"column:error_message;type:text"`
	RetryCount  int            `json:"retry_count" gorm:"default:0"`
	Notes       string         `json:"notes" gorm:"type:text"`
	PushedBy    uint           `json:"pushed_by" gorm:"not null"`
	PushedAt    time.Time      `json:"pushed_at"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Customer Customer `json:"customer" gorm:"foreignKey:CustomerID"`
	Partner  Partner  `json:"partner" gorm:"foreignKey:PartnerID"`
	Pusher   User     `json:"pusher" gorm:"foreignKey:PushedBy"`
}

// TableName 指定表名
func (PushRecord) TableName() string {
	return "push_records"
}

// BeforeCreate 创建前钩子
func (pr *PushRecord) BeforeCreate(tx *gorm.DB) error {
	if pr.Status == "" {
		pr.Status = "pending"
	}
	if pr.PushedAt.IsZero() {
		pr.PushedAt = time.Now()
	}
	return nil
}

// GetStatusText 获取状态文本
func (pr *PushRecord) GetStatusText() string {
	statusMap := map[string]string{
		"pending": "待推送",
		"success": "推送成功",
		"failed":  "推送失败",
		"retry":   "重试中",
	}
	if text, ok := statusMap[pr.Status]; ok {
		return text
	}
	return "未知状态"
}

// GetPushTypeText 获取推送类型文本
func (pr *PushRecord) GetPushTypeText() string {
	typeMap := map[string]string{
		"manual": "手动推送",
	}
	if text, ok := typeMap[pr.PushType]; ok {
		return text
	}
	return "未知类型"
}

// IsSuccess 检查是否推送成功
func (pr *PushRecord) IsSuccess() bool {
	return pr.Status == "success"
}

// IsFailed 检查是否推送失败
func (pr *PushRecord) IsFailed() bool {
	return pr.Status == "failed"
}

// CanRetry 检查是否可以重试
func (pr *PushRecord) CanRetry() bool {
	return pr.IsFailed() && pr.RetryCount < 3
}

// UpdateStatus 更新推送状态
func (pr *PushRecord) UpdateStatus(db *gorm.DB, status string, response string, errorMsg string) error {
	pr.Status = status
	pr.Response = response
	pr.ErrorMsg = errorMsg
	pr.UpdatedAt = time.Now()
	return db.Save(pr).Error
}

// IncrementRetry 增加重试次数
func (pr *PushRecord) IncrementRetry(db *gorm.DB) error {
	pr.RetryCount++
	pr.Status = "retry"
	pr.UpdatedAt = time.Now()
	return db.Save(pr).Error
}

// MarkSuccess 标记为成功
func (pr *PushRecord) MarkSuccess(db *gorm.DB, response string) error {
	return pr.UpdateStatus(db, "success", response, "")
}

// MarkFailed 标记为失败
func (pr *PushRecord) MarkFailed(db *gorm.DB, errorMsg string) error {
	return pr.UpdateStatus(db, "failed", "", errorMsg)
}